<template>
  <base-breadcrumb>
    <searchData :searchData="searchArr" @search="search"></searchData>
    <a-card :bordered="false">
      <list-table
        ref="table"
        :columns="columns"
        :request="loadData"
        :exportConfig="{ use: true, select: '导出选中', all: '导出全部' }"
      >
        <template slot="prefix">
          <ExcelImportButton icon="import" @handleSubmit="handleImport" :loading="loading">导入</ExcelImportButton>
          <export-mould
            style="margin-left: 5px"
            templateCode="中建八局困难职工统计表模板.xlsx"
            icon="cloud-download"
          ></export-mould>
        </template>
        <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
        <template slot="createTime" slot-scope="text, record">
          {{ record.createTime | dateFormat('D') }}
        </template>
        <template slot="entryTime" slot-scope="text, record">
          {{ record.entryTime | dateFormat('D') }}
        </template>
        <template slot="auditStatusStr" slot-scope="text, record">
          <list-status :status="record.auditStatus" :text="text"></list-status>
        </template>
        <template slot="operation" slot-scope="text, record">
          <MoreButton class="pub-table-list-action">
            <a
              v-btn-permission="'lu_0010_loo_04'"
              @click="$nav('/union/employeeCare/difficultiesEmployeesApply/add', { id: record.id, detail: 1 })"
              >查看</a
            >
            <approval-button :status="record.auditStatus" :id="record.id"
                             v-if="record.auditStatus === 'PAST' || record.auditStatus === 'SUBMITTED' || record.auditStatus === 'REJECTED' || record.auditStatus === 'REVOKEIN' || record.auditStatus === 'REVOKE' || record.auditStatus === 'ABOLISH' || record.auditStatus === '1' || record.auditStatus === '3' || record.auditStatus === 'COMMIT'|| record.auditStatus === '2' "
            ></approval-button>
          </MoreButton>
        </template>
      </list-table>
    </a-card>
    <ExportResult :visible.sync="visibleExport" :exportList="exportList" width="80%" />
  </base-breadcrumb>
</template>

<script>
import hardWorkApi from '@/api/union/employeeCare/hardWorkApi'
import ExportMould from '@/components/ExportMould'
import ExportResult from '@/components/Dialog/ExportResult' // 导出结果弹窗

export default {
  name: 'a' + Date.now(),

  components: {
    ExportMould,
    ExportResult
  },
  data() {
    return {
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '层级',
          dataIndex: 'levelName',
          width: 150
        },
        {
          title: '单位',
          dataIndex: 'depName',
          width: 120
        },
        {
          title: '姓名',
          dataIndex: 'name',
          width: 150
        },
        {
          title: '性别',
          dataIndex: 'sex',
          width: 150
        },
        {
          title: '身份证号码',
          dataIndex: 'idCard',
          width: 180
        },
        {
          title: '困难级别',
          dataIndex: 'hardLevel',
          width: 150
        },
        {
          title: '入职时间',
          dataIndex: 'entryTime',
          scopedSlots: { customRender: 'entryTime' },
          width: 150
        },
        {
          title: '申请时间',
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'createTime' },
          width: 150
        },
        {
          title: '审核状态',
          dataIndex: 'auditStatusStr',
          scopedSlots: { customRender: 'auditStatusStr' },
          width: 150
        },
        {
          title: '操作',
          width: 200,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      searchArr: [
        // 搜索框
        {
          name: '姓名',
          type: 'input',
          value: 'name'
        },
        {
          name: '困难级别',
          value: 'hardLevel',
          type: 'select',
          data: [
            { value: '公司工会帮扶', label: '公司工会帮扶' },
            { value: '局工会帮扶', label: '局工会帮扶' }
          ]
        },
        {
          name: '层级',
          type: 'select',
          value: 'level',
          data: []
        },
        {
          name: '单位',
          type: 'input',
          value: 'depName'
        }
      ],
      loadData: (params) => {
        return hardWorkApi.getPageList(Object.assign(params, { query: this.queryParam }))
      },
      queryParam: {},
      loading: false, // 导入loading
      visibleExport: false, // 导入结果弹窗控件
      exportList: [{ columns: [], datas: [] }] // 导入配置项
    }
  },
  created() {
    this.getTypeLabel({ type: 1 })
  },
  methods: {
    async handleImport(e) {
      let columns = [
        { title: '所在单位', dataIndex: 'depName' },
        { title: '姓名', dataIndex: 'name' },
        { title: '性别', dataIndex: 'sex' },
        { title: '家庭人口', dataIndex: 'familyNum' },
        { title: '家庭月收入（元）', dataIndex: 'familyMonthlyIncome' },
        { title: '人均月收入（元）', dataIndex: 'avgMonthlyIncome' },
        { title: '当地最低工资标准（元/月）', dataIndex: 'lastSalary' },
        { title: '致困原因 ', dataIndex: 'hardResult', ellipsis: true },
        { title: '身份证号码', dataIndex: 'idCard' },
        { title: '联系电话', dataIndex: 'telphone' },
        {
          title: '帮扶类别',
          dataIndex: 'hardLevel',
          options: ['局工会重点帮扶', '公司工会帮扶'],
          excelConfig: {
            dataValidation: {
              type: 'list'
            }
          }
        },
        { title: '帮扶时间', dataIndex: 'createTime' },
        { title: '备注', dataIndex: 'remark' }
      ]
      let newTable = []
      //   this.$console(e)
      e.map((row) => {
        let temp = {}
        for (const rowKey in row) {
          let column = columns.find((columnRow) => columnRow.title === rowKey)
          if (column) {
            let dataIndex = column.dataIndex
            temp[dataIndex] = row[rowKey]
          }
        }
        if (temp.createTime) {
          temp.createTime = new Date(temp.createTime).valueOf()
        }
        newTable.push(temp)
      })
      this.$console(newTable)

      this.loading = true
      let res = await hardWorkApi.addList(newTable)
      this.loading = false
      if (res.code === 200) {
        // 若错误列表存在数据
        if (res.data?.studioDtos?.length) {
          // 导出错误文件表格配置表
          let columnsExport = [
            { title: '序号', width: 80, dataIndex: 'index', customRender: (text, record, index) => index + 1 },
            ...columns,
            { dataIndex: 'msg', ellipsis: true, title: '失败原因' }
          ]
          // 转换时间戳为字符串
          res.data.studioDtos.forEach((i) => {
            i.id = i.id || Date.now()
            i.createTime = this.$dateFormat(i.createTime, 'D')
          })
          // 设置导出结果配置项
          this.exportList = [
            {
              successCount: res.data.successCount,
              columns: columnsExport,
              datas: res.data.studioDtos
            }
          ]
          // 打开导出结果弹窗
          this.visibleExport = true
        } else {
          this.$message.success('导入成功')
        }
        // 如果有导入成功条数，则刷新表格
        res.data?.successCount > 0 && this.search()
      }
      //   this.search()
      //   this.$notification.open({ message: '提示', duration: null, description: () => <pre>{res.message}</pre> })
      // console.log(newTable)
    },
    search(val) {
      this.queryParam = val || {}
      this.$refs.table.getData(null, true)
    },
    handleDel(id) {
      this.$delList3(
        hardWorkApi.delete,
        () => {
          this.search()
        },
        { id }
      )
    },
    async getTypeLabel(args) {
      const { unionApiUrl } = require('@/api/config.js')
      const Union = require('@/api/union').default
      const { getLabels } = new Union(unionApiUrl, 'queryTypesLabelList')
      let res = await getLabels(args)
      this.searchArr[2].data = res.data ? res.data : []
      this.searchArr[2].data = this.searchArr[2].data.map((v) => {
        return { label: v.name, value: v.id }
      })
    }
  }
}
</script>
